// npm 包
import React, { useState, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { AutoComplete, Button, message, Select, Descriptions, Modal } from 'antd';
import { history } from 'umi';
import {
  DrawerForm, ProFormSelect, ProFormRadio, ModalForm, ProFormText, ProFormTextArea
} from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
const { Option } = Select;
// 数据请求
import { studentTagList, updateTag, getValueAndTextList, getGroupListByAid, exportList } from './service';
import { DICT_TYPE, getOptions, getStudentSearchOptions, selectStudent } from '@/global/service';
// 辅助函数+自定义枚举
import type { TableListItem } from './data.d';
import { blobToJson } from '@/utils/export';
import { checkTime } from '@/global/validation';
import { onRequestNickName } from '@/utils/requestPhone';
import ExportButton from '@/components/ExportButton';
import { baseUrl } from '@/utils/httpUrl';

const BlankComp = () => {
  return <></>;
};
// const { id : courseId } = history.location.query || {};
const TableList: React.FC<{}> = () => {
  const { activityId, paperId } = history.location.query || {}
  const actionRef = useRef<ActionType>();
  const [statusTab, setStatusTab] = useState<number | null>(1);
  const [statusList, setStatusList] = useState<any>();
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [classOptions, setClassOptions] = useState<{ value: string }[]>([]);
  const [level, setLevel] = useState<{ value: string }[]>([]);
  const [uid, setUid] = useState<number | null>();
  const [paperName, setPaperName] = useState();
  const [paperLevel, setPaperLevel] = useState();
  const [startTimeStr, setStartTimeStr] = useState();
  const [topPaperId, setPaperId] = useState();

  const [phoneValue, setPhoneValue] = useState<any>();


  useEffect(() => {
    fetchStatus()
    fetchGroupStatus()
  }, []);

  const fetchStatus = async () => {
      const res = await getValueAndTextList({code:'level_tag'});
      let arr = [{
        label: '无',
        value: '',
        key: '0',
      }]
      const optionList = res.result.map((item: any) => ({
        // id: item.id,
        label: `${item.des}`,
        value: `${item.value}`,
        key: `${item.value}`,
      }));
      arr = arr.concat(optionList)
      console.log(optionList)
      setLevel(arr);
    };

    const fetchGroupStatus = async () => {
      const resGroup = await getGroupListByAid({activityId});
      const optionList = resGroup.result.map((item: { id: any; name: any;}) => ({
            // id: item.id,
            label: `${item.id}-${item.name}`,
            value: `${item.id}`,
            key: `${item.id}`,
          }));
          console.log(optionList)
      setClassOptions(optionList);
    };



  const onReload = () => {
    // fetchStatus(null);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const handleChange =  async (value: any,id: number) => {
    console.log(value,id); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
    const res = await updateTag({tag:value,uid:id,paperId});
    if (res.code === 200) {
      onReload();
      message.success('修改成功');
    } else {
      message.error(res.message);
    }
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '用户昵称',
      dataIndex: 'userName',
      hideInForm: true,
      hideInSearch: true,
    },
    
    {
      dataIndex: 'uid',
      hideInTable: true,
      title: '昵称/手机号',
      ellipsis: true,
      align: 'center',
      renderFormItem: () => {
        return (
          <div>
            <ProFormSelect
              // wrapperCol={{ span: 24 }}
              // labelCol={{ span: 24 }}
              name="uid"
              showSearch
              fieldProps={{
                onChange: (val) => setPhoneValue(val)
              }}
              // labelAlign="left"
              // debounceTime={500}
              placeholder="请选择"
              request={onRequestNickName}
            />
          </div>
        );
      },
    },


    {
      title: '手机号',
      dataIndex: 'phone',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupId',
      hideInTable: true,
      // order: 90,
      // formItemProps: { labelCol: { span: 8 } },
      renderFormItem: () => (
        <Select
        style={{ width: 120 }}
        options={classOptions}
         />
      ),
    },

    {
      title: '辅导老师',
      dataIndex: 'counselor',
      hideInSearch: true,
    },
    {
      title: '作答次数',
      dataIndex: 'count',
      hideInSearch: true,
    },
    {
      title: '正确率（首次）',
      dataIndex: 'firstScore',
      hideInSearch: true,
    },
    {
      title: '正确率（末次）',
      dataIndex: 'lastScore',
      hideInSearch: true,
    },

    {
      title: '用户水平',
      dataIndex: 'tag',
      hideInSearch: true,
      render: (_, record) => (
        <Select
        defaultValue={record.tag}
        style={{ width: 120 }}
        options={level}
        onChange={(value) => {
          handleChange(value,record.id)
        }}
         />
      ),
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <a
              target="_blank"
              href={baseUrl.webview + `/computation_student_paper?isTeacher=1&uid=${record.uid}&paperId=${paperId}`}
              rel="noreferrer"
            >
              查看试卷
            </a>
      ),
    },
  ];

  // useEffect(() => {
  //   fetchStatus(null);
  // }, []);
  // const fetchStatus = async (gameId) => {
  //   const res = await listAiGameStatus({ uid, gameId });
  //   setStatusList(res.result);
  // };
  const exportPaperList = async () => {
    // setLoading(true);
    const res = await exportList({paperId});
    console.log(res)
    // blobToJson(res, 'test');
    // setLoading(false);
  }

  return (
    <>
      <Descriptions
      title={paperName}
      extra={
        <ExportButton
              fileName={`${paperName}`}
              type="tagList"
              fileType="xls"
              data={{paperId}}
              key="btn2"
              render={<Button type="primary">导出试卷数据</Button>}
            />
      }
      style={{backgroundColor: '#fff',padding:'20px 20px 4px',marginBottom:20}}
       column={4}>
        <Descriptions.Item label="试卷ID">{topPaperId}</Descriptions.Item>
        <Descriptions.Item label="试卷名称">{paperName}</Descriptions.Item>
        <Descriptions.Item label="试卷开始时间">{paperLevel}</Descriptions.Item>
        <Descriptions.Item label="难度">{startTimeStr}</Descriptions.Item>
      </Descriptions>
      <ProTable<TableListItem>
        actionRef={actionRef}
        request={async (params) => {
          console.log(params)
          // return
          const msg = await studentTagList({
            uid: phoneValue,
            paperId,
            pageNo: params.current,
            pageSize: params.pageSize,
            groupId: params.groupId,
          });
          setPaperId(msg.result.paperId)
          setPaperName(msg.result.name)
          setPaperLevel(msg.result.level)
          setStartTimeStr(msg.result.startTimeStr)
          return {
            data: msg.result.userPaperList,
            success: true,
            total: msg.result.total,
          };
        }}
        onReset={() => {
          setStatusTab(1);
          setUid(null);
          onReload();
        }}
        onSubmit={async (params) => {
          console.log(params);
          fetchStatus(params.gameId);
        }}
        columns={columns}
        beforeSearchSubmit={(params) => {
          if (
            params.starttimeStr &&
            params.endtimeStr &&
            !checkTime(params.starttimeStr, params.endtimeStr)
          ) {
            return {};
          } else {
            return params;
          }
        }}
        search={{
          collapsed: false,
          collapseRender: BlankComp,
          labelWidth: 'auto',
        }}
      />
    </>
  );
};

export default TableList;
